package com.yaoweigroup.community.ui.base;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.ui.MainTabActivity;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 用户登陆
 * 
 * @author xi
 * 
 */
public class LoginActivity extends Activity implements OnClickListener {

	private TextView reg_tv;
	private Intent intent;
	private TextView reset_tv;
	private RelativeLayout left_rl;

	private Dialog dialog;
	private Button loginBtn;

	private EditText name_et;
	private EditText pass_et;

	public final int LOGIN_SUCCESS = 0x2210;
	public final int LOGIN_FAIL = LOGIN_SUCCESS + 1;
	private ObjectMapper mapper;
	private SharePreferenceUtil util;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		util = new SharePreferenceUtil(this, Constant.prf);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;

		mapper = new ObjectMapper();
		name_et = (EditText) findViewById(R.id.name_et);
		pass_et = (EditText) findViewById(R.id.pass_et);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setOnClickListener(this);
		reset_tv = (TextView) findViewById(R.id.reset_tv);
		reset_tv.setOnClickListener(this);

		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		loginBtn = (Button) findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(this);
		dialog = DialogUtil.createWaitDialog(this, "登陆中..");
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.reg_tv:
			intent = new Intent(this, RegActivity.class);
			startActivity(intent);
			break;
		case R.id.reset_tv:
			intent = new Intent(this, PassUpdateActivity.class);
			startActivity(intent);
			break;
		case R.id.left_rl:
			finish();
			break;
		case R.id.loginBtn:
			login();
			break;
		}
	}

	private void login() {

		String name = name_et.getText().toString();
		String pass = pass_et.getText().toString();
		if (name.length() == 0 || pass.length() == 0) {
			Toast.makeText(this, "账号或密码不能为空!", 500).show();
			return;
		}
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("UserName", name);
		jsonUtil.add("PassWord", pass);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.login, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							String message = obj.getString("message");
							if (state == 200) {

								UserInfo userInfo = mapper.readValue(data,
										new TypeReference<UserInfo>() {
										});
								util.saveObject(userInfo, "user");
								handler.sendEmptyMessage(LOGIN_SUCCESS);

							} else {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(LOGIN_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case LOGIN_SUCCESS:
				finish();
				break;
			case LOGIN_FAIL:
				String error = "登陆失败!";
				if (msg.obj != null) {
					error = msg.obj.toString();
				}
				Toast.makeText(LoginActivity.this, error, 500).show();
				break;
			}

		};
	};

}
